<template>
  <a-form
    ref="formRef"
    :model="data.formData"
    :label-col-props="{ span: autoSpan.labelSpan }"
    :wrapper-col-props="{ span: autoSpan.wrapperSpan }"
    label-align="right"
    @submit="search"
    class="form-column"
  >
    <a-row>
      <a-col :flex="1">
        <a-row overflow-hidden :gutter="16">
          <a-col
            v-for="(item, index) in props.columns"
            :key="index"
            :span="rowSpan || autoSpan.rowSpan"
            overflow-hidden
          >
            <a-form-item :field="item.model">
              <template #label :label="item.label">
                <a-tooltip :content="item.label"><div text-13px cursor-pointer>{{ item.label }}</div></a-tooltip>
              </template>
              <!-- 输入框 input -->
              <a-input
                v-if="item.input"
                v-model="data.formData[item.model]"
                :disabled="item.disabled"
                :placeholder="'请输入' + item.label"
                allow-clear
              />
              <!-- 选择框 select -->
              <a-select
                v-if="item.select"
                v-model="data.formData[item.model]"
                :disabled="item.disabled"
                :placeholder="'请选择' + item.label"
              >
                <a-option
                  v-for="(key, idx) in item.select.options"
                  :key="idx"
                  :label="key.label"
                  :value="key.value"
                >
                </a-option>
              </a-select>
              <!-- 日期选择框 -->
              <a-range-picker
                v-if="item.datePicker"
                v-model="data.formData.$date"
                :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }"
                :disabled-date="disabledTime"
                style="width: 360px;"
                :show-time="props.timeType === 'timestamp' || props.timeShow"
              />

              <!-- 商品分类选择器   -->
              <a-cascader
                v-if="item.category"
                v-model:model-value="data.categoryIds"
                placeholder="选择商品分类"
                :loading="data.categoryLoading"
                :options="data.categoryData"
                :field-names="fieldNames"
                @click="handleClickCategory"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-col>

      <a-divider style="height: 84px" direction="vertical" />
      <a-col :flex="'86px'" style="text-align: right">
        <a-space direction="vertical" :size="18" style="padding-bottom: 16px">
          <a-button type="primary" html-type="search">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
          <a-button @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </a-col>
    </a-row>
  </a-form>
  <a-divider style="margin-top: 0" />
</template>

<script lang="ts" setup>
  // https://dayjs.gitee.io/zh-CN/
  import { getLabelData } from '@/api/goods';
  import { useUserStore } from '@/store/index';
  import { dayFormatHHssMM } from '@/utils/filters';
  import dayjs from 'dayjs';
  import { reactive, ref, watch, onMounted } from 'vue';
  import { useResizeObserver } from '@vueuse/core'

  const props = withDefaults(
    defineProps<{
      columns: any[];
      rowSpan?: number;
      timeType?: 'date' | 'timestamp';
      timeShow?: boolean;
    }>(),
    {
      timeType: 'date',
    }
    
  );
  const autoSpan = ref<{
    labelSpan: number;
    wrapperSpan: number;
    rowSpan: number
  }>({
    labelSpan:9,
    wrapperSpan:15,
    rowSpan:6
  });
  // 用于接收以及返回的form表单
  const data = reactive<any>({
    formData: {
      $date: [],
      startDate: '',
      endDate: '',
    },

    categoryLoading: false, // 分类加载
    categoryData: [], // 分类数据
    categoryIds: [], // 选择的分类id
  });
  const formRef = ref();
  /**
   * 回调给父级
   * search 点击查询返回的信息
   * reset  点击清空返回信息
   *
   * */
  const emits = defineEmits<{
    (e: 'search', obj: object): void;
    (e: 'reset', obj: object): void;
    (e: 'categoryList', obj: object): void;
  }>();
  // 自定义字段名
  const fieldNames = { value: 'id', label: 'name' };
  const labelData = ref([]);

  
  // 重置
  const reset = () => {
    formRef.value.resetFields(); // 清空表单

    data.categoryIds = []; // 清空分类选择器
    if (props.timeType === 'date') {
      data.formData.startDate = '';
      data.formData.endDate = '';
      delete data.formData.startTime;
      delete data.formData.endTime;
    } else {
      data.formData.startTime = '';
      data.formData.endTime = '';
      delete data.formData.startDate;
      delete data.formData.endDate;
    }
    data.formData.$date = []; // 清空时间选择器
    emits('reset', data.formData);
  };
  // 搜索
  const search = () => {
    // 最终将有值的结果返回给父级别
    const submitData = JSON.parse(JSON.stringify(data.formData));
    // 如果选择了时间 解析时间
    if (submitData.$date && submitData.$date.length) {
      if (props.timeType === 'date') {
        submitData.startDate = dayFormatHHssMM(submitData.$date[0]);
        submitData.endDate = dayFormatHHssMM(submitData.$date[1]);
        delete submitData.startTime;
        delete submitData.endTime;
      } else {
        submitData.startTime = new Date(submitData.$date[0]).getTime();
        submitData.endTime = new Date(submitData.$date[1]).getTime();
        delete submitData.startDate;
        delete submitData.endDate;
      }
    }
    delete submitData.$date;
    emits('search', submitData);
  };

  // 禁用时间
  function disabledTime(current: any) {
    return props.timeType === 'timestamp'
      ? false
      : dayjs(current).isAfter(dayjs());
  }

  // 递归出没有child的子集
  const deepEmptyChildren = (list: any[]) => {
    if (list.length) {
      list.forEach((item) => {
        if (item.children) {
          !item.children.length
            ? delete item.children
            : deepEmptyChildren(item.children);
        }
      });
      return list;
    }
    return list;
  };

  const userStore = useUserStore();
  // 点击分类选择器
  const handleClickCategory = async () => {
    data.categoryLoading = true;
    // await userStore.fetchGoodsCategory();
    data.categoryLoading = false;
    // if (userStore.getGoodsCategory.length) {
    //   deepEmptyChildren(userStore.getGoodsCategory);
    // }
    // data.categoryData = userStore.getGoodsCategory;

    // 获取分类数据
    getLabelData().then((res) => {
      if (res.data.success) {
        data.categoryData = res.data.result.map((item: any) => {
          item.name = item.labelName;
          if (item.children && item.children.length) {
            item.children.map((childItem: any) => {
              childItem.parentId = item.id;
              childItem.name = childItem.labelName;
              return childItem;
            });
          } else {
            item.children = null;
          }
          return item;
        });
        data.categoryData.unshift({
          children: null,
          id: '',
          labelName: '全部商品',
          level: 0,
          name: '全部商品',
          sortOrder: 1,
        });
      }
    });
  };

  // 商品分类进行点击的时候进行回调
  watch(
    () => {
      data.categoryIds;
    },
    () => {
      emits('categoryList', data.categoryIds);
    },
    { deep: true }
  );
  

  
  
onMounted(() => {
  // 通过useResizeObserver监听dom变化更改列表的行数
  useResizeObserver(formRef, (entries) => {
    const entry = entries[0]
    const { width } = entry.contentRect
    
    if(width <= 600){
      autoSpan.value.rowSpan = 24
      autoSpan.value.labelSpan = 6

      autoSpan.value.wrapperSpan = 18
      return
    }
    if(width > 600 && width < 899){
      autoSpan.value.rowSpan = 12
      autoSpan.value.labelSpan = 8
      autoSpan.value.wrapperSpan = 16
      return
    }
    if(width < 1499 && width > 800){
      autoSpan.value.rowSpan = 8
      autoSpan.value.labelSpan = 9
      autoSpan.value.wrapperSpan = 15
      return
    }

    if(width >= 1500 ){
      autoSpan.value.rowSpan = 6
      autoSpan.value.labelSpan = 6
      autoSpan.value.wrapperSpan = 18
      return
    }
  })
});
</script>

<style lang="less">
  .form-column {
    .arco-form-item {
      box-sizing: border-box;
      border: 1px solid #dde2e9;
      border-radius: 4px;
      margin-bottom: 14px;
      display: flex;
      flex-wrap: nowrap;
      > .arco-col:nth-of-type(1) {
        border-right: 1px solid #dde2e9;
        display: inline-block;
        width: auto;
        flex: none;
        max-width: 30%;
        box-sizing: border-box;
        padding: 0 10px;
        .arco-form-item-label {
          width: 100%;
          overflow: hidden;
          -webkit-line-clamp: 1;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          /*white-space: pre-wrap;*/
          /*text-align: right;*/
        }
      }
      > .arco-col:nth-of-type(2) {
        width: 100%;
        flex: auto;
      }
      .arco-input, .arco-input-wrapper, .arco-picker, .arco-select, .arco-select-view-value, .arco-select-view {
        background-color: transparent;
        font-size:13px;
      }
      input::-webkit-input-placeholder, textarea::-webkit-input-placeholder,
      input:-moz-placeholder, textarea:-moz-placeholder,
      input::-moz-placeholder, textarea::-moz-placeholder,
      input:-ms-input-placeholder, textarea:-ms-input-placeholder {
        font-size:13px;
      }
    }
  }
</style>
